package BanyuanClub.Study.Day0308.多线程.习题二;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 用三个线程计算1 - 100；
 * 1-33
 * 34-66
 * 67-100
 * 用循环创建线程
 */
public class Text {
    public void createThread(int n) throws ExecutionException, InterruptedException {
        int avg = 100/3;
        FutureTask[] ftarr = new FutureTask[3];
        for (int i = 0; i < 3; i++) {
            int index = i;
            FutureTask<Integer> ft = new FutureTask<Integer>(() -> {
                int sum = 0;
                int start = index * avg + 1;
                int end = index < 2 ? start + avg - 1 : 100;
                for (int j = start; j <= end; j++) {
                    sum += j;
                }
                return sum;
            });
            ftarr[i] = ft;
        }

        for (FutureTask<Integer> ft:ftarr
             ) {
            new Thread(ft).start();
        }
        int all = 0;
        for (FutureTask<Integer> ft:ftarr
             ) {
            all += ft.get();
        }

        System.out.println("总和为：" + all);
    }
}
